<template>
  <n-grid :x-gap="30" :y-gap="10" cols="2 900:4">
    <template v-for="item of books" :key="item._id">
      <n-grid-item class="point">
        <n-card @click="$router.push(`/book/${item._id}`)" :title="item.name">
          <template #cover>
            <img :src="`${host}${item.image}`" />
          </template>
          <n-ellipsis :line-clamp="4">
            {{ item.description }}
          </n-ellipsis>
        </n-card>
      </n-grid-item>
    </template>
  </n-grid>
  <div class="mt-5 flex flex-jc-center">
    <n-pagination
      v-model:page="page"
      v-model:page-size="pageSize"
      :page-count="totalPage"
      show-size-picker
      :page-sizes="[8, 16, 24, 32]"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, toRefs, watch, watchEffect } from "vue";
import { NGrid, NGridItem, NCard, NEllipsis, NPagination } from "naive-ui";

import { useBooks } from "../hooks/UseBooks";

export default defineComponent({
  name: "Search",
  components: { NGrid, NGridItem, NCard, NEllipsis, NPagination },
  props: {
    bookName: {
      type: String,
      default: "",
    },
  },
  setup(props) {
    const { bookName } = toRefs(props);
    const { books, getAllBooks } = useBooks();
    const host = ref(import.meta.env.VITE_SEREVER_HOST as string);
    const page = ref(1);
    const pageSize = ref(16);
    const totalPage = ref(0);

    watchEffect(async () => {
      const t = await getAllBooks(bookName.value, page.value, pageSize.value);
      totalPage.value = Math.floor(t / pageSize.value) + 1;
    });
    watch(bookName, () => {
      page.value = 1;
    });

    return {
      host,
      books,
      getAllBooks,
      page,
      pageSize,
      totalPage,
    };
  },
});
</script>

<style scoped>
.point {
  cursor: pointer;
}
</style>
